﻿using System.Net;
using System.Net.Sockets;
using Microsoft.Extensions.Options;
using NModbus;
using qYun.ApiService.Models;
using GasModel = qYun.Shared.Models.GasModel;

namespace qYun.ApiService.Services;

/// <summary>
/// 
/// </summary>
public class GasService:IGasService
{
    private ILogger<GasService> _logger;
    public required SystemConfig _config;
    public required IModbusMaster _master;
    private readonly IDbService _dbService;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="logger"></param>
    /// <param name="config"></param>
    /// <param name="dbService"></param>
    public GasService(ILogger<GasService> logger,IOptions<SystemConfig> config,IDbService dbService)
    {
        _logger = logger;
        _config = config.Value;
        _dbService = dbService;
        var sock = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
        var gasIp = _config.GasContent?.DeviceIp;
        var gasPort = _config.GasContent?.DevicePort;
        if(gasIp is null|| gasPort is null)
        {
            _logger.LogError("含气量检测装置IP地址为空");
            return ;
        }

        // var serverFullAddr = new IPEndPoint(IPAddress.Parse(gasIp), int.Parse(gasPort));
        // sock.Connect(serverFullAddr);
        //
        // var factory = new ModbusFactory();
        // _master = factory.CreateMaster(sock);
    }
    
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public async Task<GasModel> GetDataAsync()
    {
        try
        {
            var model = new GasModel();
            var slaveId = _config.GasContent?.SlaveId;
            await Task.Run(async () =>
            {
                if (slaveId != null)
                {
                    var res = await _master.ReadHoldingRegistersAsync(byte.Parse(slaveId), 0x0004, 12);
                    var i = 0;
                    model.CurrentStatus = (int)(res[i] << 16 | res[1]);
                    i += 2;
                    model.EnvironmentTemperature = BitConverter.ToSingle(BitConverter.GetBytes((int)(res[i] << 16 | res[i + 1])), 0);
                    i += 2;
                    model.AtmosphericPressure = BitConverter.ToSingle(BitConverter.GetBytes((int)(res[i] << 16 | res[i + 1])), 0);
                    i += 2;
                    model.DegassingTemperature = BitConverter.ToSingle(BitConverter.GetBytes((int)(res[i] << 16 | res[i + 1])), 0);
                    i += 2;
                    model.DataAnalysisCount = (int)(res[i] << 16 | res[i + 1]);
                    i += 2;
                    model.GasContent = BitConverter.ToSingle(BitConverter.GetBytes((int)(res[i] << 16 | res[i + 1])), 0);
                }
            });
            return model;
        }
        catch(Exception e)
        {
            _logger.LogError(e,"含气量检测装置读取出错");
            return new GasModel();
        }
    }

    public async Task InsertGasDataToDbAsync(GasModel gasModel)
    {

        await _dbService.InsertGasDataAyync(gasModel);
    }
}

/// <summary>
/// 
/// </summary>
public interface IGasService
{
    /// <summary>
    /// 
    /// </summary>
    /// <returns></returns>
    public Task<GasModel> GetDataAsync();

    public Task InsertGasDataToDbAsync(GasModel gasModel);
}